package com.town.garden.component;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.town.garden.chain.AbstractServerStartHandler;
import com.town.garden.constant.GlobalConstant;
import com.town.garden.entiy.ChannelInfo;
import com.town.garden.entiy.StreamInfo;
import com.town.garden.enums.DeviceStatusEnum;
import com.town.garden.enums.NVRApiEnum;
import com.town.garden.propertites.NvrProperties;
import com.town.garden.service.ZLMediaKitService;
import com.town.garden.service.impl.NvrSystemInfoServiceImpl;
import com.town.garden.storage.NvrSessionStorage;
import com.town.garden.utils.PulsarInitUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @Description 心跳组件
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/5/13
 */
@Slf4j
@Component(HeartbeatComponent.BEAN_NAME)
public class HeartbeatComponent extends AbstractServerStartHandler implements Runnable {
    /**
     * 下一个执行链对象
     * {@linkplain NvrSystemInfoServiceImpl}
     */
    @Autowired
    @Qualifier(NvrSystemInfoServiceImpl.BEAN_NAME)
    private AbstractServerStartHandler abstractServerStartHandler;
    public static final String BEAN_NAME = "heartbeatComponent";
    @Autowired
    private NvrProperties nvrProperties;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ZLMediaKitService zlMediaKitService;
    @Autowired
    private ScheduledExecutorService scheduledExecutorService;
    @Autowired
    private PulsarInitUtil pulsarInitUtil;

    @Override
    public void handlerOperation() {
        //提交定时任务
        ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(this, 0, nvrProperties.getHeartBeatInterval(), TimeUnit.SECONDS);
        //调用下个链执行
        abstractServerStartHandler.handlerOperation();
    }

    @Override
    public void run() {
        //请求url拼装
        final String url = GlobalConstant.HTTPS_PREFIX + nvrProperties.getNvrServerIp() + NVRApiEnum.HEARTBEAT.getUrl();
        //拼装请求头
        Map<String, Object> map = new HashMap<String, Object>(16);
        map.put("data", null);
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.ACCEPT, MediaType.ALL_VALUE);
        headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
        headers.set(HttpHeaders.COOKIE, NvrSessionStorage.strCookie);
        headers.set(GlobalConstant.X_CSRF_TOKEN, NvrSessionStorage.strXCsrfToken);
        HttpEntity<?> entity = new HttpEntity<>(map, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        log.info("send nvr server Heartbeat ,response is :{}", exchange.getBody());
        List<Map<String, Object>> data = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(NvrSessionStorage.CHANNEL_IP_MAP)) {
            for (String key : NvrSessionStorage.CHANNEL_IP_MAP.keySet()
            ) {
                ChannelInfo channelInfo = NvrSessionStorage.CHANNEL_IP_MAP.get(key);
                if ((DeviceStatusEnum.ONLINE.getStatus().equals(channelInfo.getStatus()))) {
                    Map<String, Object> info = new HashMap<>(16);
                    info.put("deviceNo", nvrProperties.getMac() + GlobalConstant.SPLIC_STR + channelInfo.getIpAddress());
                    info.put("nvrMac", nvrProperties.getMac());
                    //获取直播地址
                    List<StreamInfo> mediaList = zlMediaKitService.getMediaList();
                    for (StreamInfo streamInfo : mediaList
                    ) {
                        if (key.equals(streamInfo.getApp())) {
                            info.put("videoUrl", streamInfo.getFlv());
                        }
                    }
                    data.add(info);
                }
            }
            log.info("--------------------->:{}",JSONUtil.toJsonStr(data));
            //发送消息给pulsar 当前设备在线状态
            pulsarInitUtil.sendMsg(IdUtil.fastSimpleUUID(), JSONUtil.toJsonStr(data), pulsarInitUtil.getProducer(GlobalConstant.VIDEO_URL_INFO));
        }
    }
}
